<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="always" header="工单统计情况">
          <el-table :data="orderstatisticsData" style="width: 100%" height="40%">
            <el-table-column fixed prop="month" label="月份" width="80" align="center" />
            <el-table-column fixed prop="county" label="区县" width="120" align="center" />
            <el-table-column prop="orderNum" label="工单总数" width="100" align="center" />
            <el-table-column prop="markOrderNum" label="采编工单总数" width="120" align="center" />
            <el-table-column prop="exitOrderNum" label="退服工单总数" width="120" align="center" />
            <el-table-column prop="markAndExitOrderNum" label="采编退服工单总数" width="140" align="center" />
            <el-table-column prop="notCloseOrderNum" label="未闭环工单数" width="140" align="center" />
            <el-table-column prop="notCloseMarkOrderNum" label="采编未闭环工单数" min-width="140" align="center" />
            <template #empty>
              <el-empty :image-size="40" />
            </template>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="always" header="工单维护指标">
          <el-table :data="orderMaintenanceData" style="width: 100%" height="40%">
            <el-table-column fixed prop="month" label="月份" width="80" align="center" />
            <el-table-column fixed prop="county" label="区县" width="120" align="center" />
            <el-table-column prop="timeOutOrderRatio" label="超时工单占比" width="150" align="center">
              <template #default="scope">
                {{ (scope.row.timeOutOrderRatio * 100).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="errorSiteRatio" label="超频故障基站占比" width="140" align="center" />
            <el-table-column prop="exitSiteRatio" label="频繁退服基站占比" min-width="140" align="center" />
            <template #empty>
              <el-empty :image-size="40" />
            </template>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-card shadow="always" header="工单详情" style="margin-top: 20px;">
          <el-form :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="归属区县：" prop="county">
              <!-- <el-input v-model="queryParams.county" placeholder="请输入所属区县" clearable style="width: 200px" /> -->
              <el-select v-model="queryParams.county" placeholder="请选择所属区县" style="width: 240px" clearable>
                <el-option v-for="item in countyOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="采编状态：" prop="markFlag">
              <el-select v-model="queryParams.markFlag" placeholder="请选择采编状态" style="width: 240px" clearable>
                <el-option v-for="item in markFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="故障类别：" prop="exitFlag">
              <el-select v-model="queryParams.exitFlag" placeholder="请选择故障类别" style="width: 240px" clearable>
                <el-option v-for="item in faultCategoryOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="清除状态：" prop="clearFlag">
              <el-select v-model="queryParams.clearFlag" placeholder="请选择清除状态" style="width: 240px" clearable>
                <el-option v-for="item in faultEliminateFlagOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间：" prop="createTime">
              <el-date-picker v-model="queryParams.createStartEnd" type="daterange" range-separator="To"
                start-placeholder="开始时间" end-placeholder="结束时间" :size="size" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="listEomsOrderTable">查询</el-button>
              <el-button @click="unsetQueryForm"><el-icon>
                  <RefreshRight />
                </el-icon>重置</el-button>
              <el-button type="primary" icon="Upload" @click="importData">导入</el-button>
              <el-button type="primary" icon="Download" @click="exportData">导出</el-button>
            </el-form-item>

          </el-form>
          <el-table :data="eomsOrderData" style="width: 100%">
            <el-table-column fixed prop="orderId" label="工单号" width="250" align="center" />
            <el-table-column prop="county" label="归属区县" width="120" align="center" />
            <el-table-column prop="stationId" label="站号" width="120" align="center" />
            <el-table-column prop="neName" label="小区名称" width="200" align="center" />
            <el-table-column prop="markFlag" label="是否采编" width="150" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.markFlag === 1 ? '' : 'success'" disable-transitions>{{ scope.row.markFlag ==
      1 ? "是" : "否" }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="orderCreateTime" label="工单生成时间" :formatter="dateFormatter" width="250"
              align="center" />
            <el-table-column prop="occurTime" label="故障发生时间" width="250" :formatter="dateFormatter" align="center" />
            <el-table-column prop="clearFlag" label="故障清除状态" width="200" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.clearFlag == 0 ? 'danger' : 'success'" disable-transitions>{{
      scope.row.clearFlag
        == 0 ? "未清除" : "已清除" }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="faultEliminateTime" label="故障清除时间" :formatter="dateFormatter" width="250"
              align="center" />
            <!-- <el-table-column prop="alarmClearTime" label="告警清除时间" :formatter="dateFormatter" width="250" align="center" /> -->

            <el-table-column prop="exitFlag" label="故障类别" width="180" align="center">
              <template #default="scope">{{ scope.row.exitFlag == 0 ? "非退服" : "退服" }}</template>

            </el-table-column>
            <el-table-column label="是否超时" width="120" align="center" fixed="right">
              <template #default="scope">
                <el-tag
                  :type="((scope.row.exitFlag == 0) && (scope.row.handleTime > 24) || (scope.row.exitFlag == 1) && (scope.row.handleTime > 8)) ? 'danger' : 'success'"
                  disable-transitions>
                  {{ ((scope.row.exitFlag == 0) && (scope.row.handleTime > 24) || (scope.row.exitFlag ==
      1) && (scope.row.handleTime > 8)) ? '超时' : '未超时' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="处理剩余时间" width="120" align="center" fixed="right">
              <template #default="scope">
                <el-tag
                  :type="((scope.row.exitFlag == 0) && (scope.row.handleTime > 24) || (scope.row.exitFlag == 1) && (scope.row.handleTime > 8)) ? '' : 'danger'"
                  disable-transitions>
                  {{ remainderFormatter(scope.row.exitFlag, scope.row.handleTime) }}
                </el-tag>
              </template>
            </el-table-column>
            <template #empty>
              <el-empty :image-size="80" />
            </template>
          </el-table>
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
            :page-sizes="[10, 50, 100, 200]" :small="small" :disabled="disabled" :background="background"
            layout="total, sizes, prev, pager, next" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </el-card>
      </el-col>
    </el-row>

    <el-dialog v-model="dialogFormVisible" v-loading="loading" title="导入数据" width="1000" ref="mv" @opened="openDialog">
      <el-tabs v-model="activeName">
        <el-tab-pane label="导入数据" name="first">
          <el-form :model="form" label-width="150px" label-position="left">
            <el-form-item label="工单数据">
              <el-button type="primary" icon="开始导入" @click="doImportEomsOrder">导入</el-button>
            </el-form-item>
            <el-form-item label="告警数据">
              <el-button type="primary" icon="开始导入" @click="doImportAlarm">导入</el-button>
            </el-form-item>
            <el-form-item label="工单计算">
              <el-button type="primary" icon="开始" @click="doCalculateOrderResult">任务开始</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="导入情况" name="second">
          <el-table :data="taskData" style="width: 100%">
            <el-table-column prop="id" label="id" width="120" align="center" />
            <el-table-column prop="taskType" label="任务类型" width="120" align="center" />
            <el-table-column prop="taskStatus" label="任务状态" width="100" align="center" />
            <el-table-column prop="startDate" label="开始时间" width="120" align="center" />
            <el-table-column prop="endDate" label="结束时间" width="120" align="center" />
            <el-table-column prop="result" label="结果" align="center" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref } from 'vue';
import { queryEomsOrderstatisticsInfo, queryEomsOrderList, queryEomsOrderMaintenanceData, importAlarm, importEomsOrder, calculateOrderResult, queryImportTaskList, exportTaskList } from '@/api/biz/maintenance';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'

const { proxy } = getCurrentInstance();


const markFlagOptions = [
  {
    value: "1",
    label: '采编',
  },
  {
    value: "0",
    label: '非采编',
  },
]

const faultCategoryOptions = [
  {
    value: "1",
    label: '退服',
  },
  {
    value: "0",
    label: '非退服',
  }
]

const faultEliminateFlagOptions = [
  {
    value: "1",
    label: '已清除',
  },
  {
    value: "0",
    label: '未清除',
  }
]

const countyOptions = [
  {
    value: "海曙区",
    label: '海曙区',
  },
  {
    value: "鄞州区",
    label: '鄞州区',
  },
  {
    value: "江北区",
    label: '江北区',
  },
  {
    value: "镇海区",
    label: '镇海区',
  },
  {
    value: "北仑区",
    label: '北仑区',
  },
  {
    value: "奉化区",
    label: '奉化区',
  },
  {
    value: "慈溪市",
    label: '慈溪市',
  },
  {
    value: "余姚市",
    label: '余姚市',
  },
  {
    value: "宁海县",
    label: '宁海县',
  },
  {
    value: "象山县",
    label: '象山县',
  }
]


const queryParams = ref(
  {
    county: undefined,
    markFlag: undefined,
    exitFlag: undefined,
    clearFlag: undefined,
    createStartEnd: undefined
  }
);
const eomsOrderData = ref([])
const orderstatisticsData = ref([])
const orderMaintenanceData = ref([])
const pageSize = ref(10)
const currentPage = ref(1)
const total = ref(0)


const dialogFormVisible = ref(false)
const activeName = ref("first")
const form = ref({})

const eomsOrderUploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/maintenance/importEomsOrder");
const alarmUploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/maintenance/importAlarm");
const dialogPanel = ref()
const mv = ref()
const taskData = ref([])


function getEomsOrderstatisticsInfo() {
  queryEomsOrderstatisticsInfo().then(response => {
    orderstatisticsData.value = response.data;
  });
}

function getEomsOrderMaintenanceData() {
  queryEomsOrderMaintenanceData().then(response => {
    orderMaintenanceData.value = response.data;
  });
}

function getEomsOrderList() {
  const param = {}
  param.pageSize = pageSize.value
  param.pageNum = currentPage.value
  queryEomsOrderList(param).then(response => {
    eomsOrderData.value = response.rows;
    total.value = response.total;
  });
}

function dateFormatter(row, column, cellValue, index) {
  if (!cellValue) { return }
  // 创建一个新的 Date 对象
  var originalDate = new Date(cellValue);

  // 获取年、月、日、时、分、秒
  var year = originalDate.getFullYear();
  var month = ("0" + (originalDate.getMonth() + 1)).slice(-2);
  var day = ("0" + originalDate.getDate()).slice(-2);
  var hours = ("0" + originalDate.getHours()).slice(-2);
  var minutes = ("0" + originalDate.getMinutes()).slice(-2);
  var seconds = ("0" + originalDate.getSeconds()).slice(-2);

  // 格式化输出
  var formattedDateTimeString = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  return formattedDateTimeString;
}

function listEomsOrderTable() {
  const param = {}
  param.county = queryParams.value.county
  param.markFlag = queryParams.value.markFlag
  param.exitFlag = queryParams.value.exitFlag
  param.clearFlag = queryParams.value.clearFlag
  //创建时间
  if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
    param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString()
    param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString()
  }
  param.pageSize = pageSize.value
  param.pageNum = currentPage.value
  queryEomsOrderList(param).then(response => {
    eomsOrderData.value = response.rows;
    total.value = response.total;
  });
}

function eomsOrderUploadSuccess(response, uploadFile, uploadFiles) {
  dialogPanel.value.close()
  var msg = ''
  if (response.data) {
    if (response.data.successFlag) {
      msg = "导入完成！总数据为" + response.data.totalNum + ",成功导入条数：" + response.data.successNum + ",失败导入条数：" + response.data.errorNum
    } else {
      msg = "导入失败！错误信息：" + response.data.errorMsg
    }
  }

  ElMessageBox.alert(msg, '导入情况', {
    confirmButtonText: 'OK',
  })
}

function eomsOrderUploadProgress(evt, uploadFile, uploadFiles) {
  dialogPanel.value = ElLoading.service({
    target: mv.value.dialogRef, // el-dialog 对象
    text: '导入中...', // Loading 的提示信息
    background: 'rgba(0,0,0,0.7)', // 设置背景颜色和透明度
  })
}

function handleSizeChange() {
  listEomsOrderTable()
}

function handleCurrentChange() {
  listEomsOrderTable()
}

//导入数据
function importData() {
  dialogFormVisible.value = true
}

function doImportEomsOrder() {
  importEomsOrder().then(response => {
    let msg = "";
    if (response.data.successFlag) {
      msg = "开始导入：任务号为" + response.data.taskNo;
    } else {
      msg = "导入失败:" + response.data.errorMsg;
    }
    ElMessageBox.alert(msg, '导入情况', {
      confirmButtonText: 'OK',
    })
  })
}

function doImportAlarm() {
  importAlarm().then(response => {
    let msg = "";
    if (response.data.successFlag) {
      msg = "开始导入：任务号为" + response.data.taskNo;
    } else {
      msg = "导入失败:" + response.data.errorMsg;
    }
    ElMessageBox.alert(msg, '导入情况', {
      confirmButtonText: 'OK',
    })
  })
}

function doCalculateOrderResult() {
  calculateOrderResult().then(response => {
    let msg = "任务开始！任务号为：" + response.data;
    ElMessageBox.alert(msg, '导入情况', {
      confirmButtonText: 'OK',
    })
  })
}

function openDialog() {
  //查询最新的任务状态
  queryImportTaskList().then(response => {
    taskData.value = response.data;
  })

}

function exportData() {
  const param = {}
  param.county = queryParams.value.county
  param.markFlag = queryParams.value.markFlag
  param.exitFlag = queryParams.value.exitFlag
  param.clearFlag = queryParams.value.clearFlag
  //创建时间
  if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
    param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString()
    param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString()
  }
  proxy.download("/maintenance/exportTaskList", {
    ...param
  }, `eoms_order_${new Date().getTime()}.xlsx`);

}

function remainderFormatter(exitFlag, handleTime) {
  if (exitFlag == 0 && handleTime < 24) {
    return (24 - handleTime).toFixed(2);
  } else if (exitFlag == 1 && handleTime < 8) {
    return (8 - handleTime).toFixed(2);
  } else {
    return 0
  }
}

function initCreateTime() {
  var today = new Date();
  var currentMonth = today.getMonth();
  var currentYear = today.getFullYear();

  var firstDayOfMonth, lastDayOfMonth;

  // 判断今天是否在5号之前
  if (today.getDate() <= 5) {
    // 如果在5号之前，返回上个月的第一天和最后一天
    if (currentMonth === 0) {
      // 如果当前月份是1月，则返回上一年的12月份
      firstDayOfMonth = new Date(currentYear - 1, 11, 1);
      lastDayOfMonth = new Date(currentYear - 1, 11, new Date(currentYear - 1, 11, 0).getDate());
    } else {
      firstDayOfMonth = new Date(currentYear, currentMonth - 1, 1);
      lastDayOfMonth = new Date(currentYear, currentMonth - 1, new Date(currentYear, currentMonth, 0).getDate());
    }
  } else {
    // 如果在5号之后，返回这个月的第一天和最后一天
    firstDayOfMonth = new Date(currentYear, currentMonth, 1);
    lastDayOfMonth = new Date(currentYear, currentMonth, new Date(currentYear, currentMonth + 1, 0).getDate());
  }
  queryParams.value.createStartEnd = [firstDayOfMonth,lastDayOfMonth]

}

getEomsOrderstatisticsInfo()
getEomsOrderMaintenanceData()
listEomsOrderTable()
initCreateTime()

</script>